import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login'
import Home from '../components/Home'
import Welcome from '../components/Welcome'
import UserList from '../components/users/UserList'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/home',
    component: Home,
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        component: Welcome
      },
      {
        path: '/users',
        component: UserList
      }
    ]
  }
]

const router = new VueRouter({
  // 去除url中的#/
  mode: 'history',
  routes
})

// 路由导航守卫
// to将要访问的路径
// from代表从哪个路径跳转来
// next是一个函数，表示放行 next()方法放行；next('/xxx')强制跳转到xxx页面
router.beforeEach((to, from, next) => {
  if (to.path === '/login') return next()
  const token = window.sessionStorage.getItem('token')
  if (!token) return next('/login')
  next()
})

export default router
